/*=============================================================================
// File Name: 
// Author:  Wood.Wang
// Date:
// Message:
// Copyright 2022,All right is reserved;
=============================================================================*/
/* Includes -----------------------------------------------------------------*/
#include "drv_i2c.h"
#include "drv_adxl345.h"


void adxl345_gpio_init(void)
{
    
}

void ADXL345_Single_Write(uint8_t REG_Address, uint8_t REG_data)
{
	I2C_WriteByte(1,ADXL345_ADDRESS,REG_Address,REG_data);
}

uint8_t ADXL345_Single_Read(uint8_t REG_Address)
{  
	uint8_t REG_data;
	REG_data = I2C_ReadByte(1,ADXL345_ADDRESS,REG_Address);
    return REG_data; 
}

int	ADXL345_GetX(void)
{
	uint8_t x[2]={0};
	I2C_PageRead(1,ADXL345_ADDRESS,ADXL345_REG_DATAX0,x,2);
	return ((int)x[0]|(x[1]<<8));
}

int	ADXL345_GetY(void)
{
	uint8_t y[2]={0};
	I2C_PageRead(1,ADXL345_ADDRESS,ADXL345_REG_DATAY0,y,2);
	return ((int)y[0]|(y[1]<<8));
}

int	ADXL345_GetZ(void)
{
	uint8_t z[2]={0};
	I2C_PageRead(1,ADXL345_ADDRESS,ADXL345_REG_DATAZ0,z,2);
	return ((int)z[0]|(z[1]<<8));
}

void  ADXL345_GetXYZ(int  *x,int *y,int  *z)
{
	uint8_t xyz[6]={0};
	I2C_PageRead(1,ADXL345_ADDRESS,ADXL345_REG_DATAX0,xyz,6);  
    if(x != NULL)   *x = (int16_t)(xyz[0]|(xyz[1]<<8));
    if(y != NULL)   *y = (int16_t)(xyz[2]|(xyz[3]<<8));
    if(z != NULL)   *z = (int16_t)(xyz[4]|(xyz[5]<<8));
    
}

uint8_t ADXL345_Init(void)
{  
   adxl345_gpio_init();
   /* Check connection */
   uint8_t deviceid = ADXL345_Single_Read(ADXL345_REG_DEVID);	//0xe5 = id
   if (deviceid != 0xE5)
   {
      /* No ADXL345 detected ... return false */
	  return 	deviceid;
   }
  
   // Enable measurements
   ADXL345_Single_Write(ADXL345_REG_DATA_FORMAT,0x09);   //+-4g range
   
   ADXL345_Single_Write(ADXL345_REG_BW_RATE,0x08);   //
   ADXL345_Single_Write(ADXL345_REG_POWER_CTL,0x08);   //
   ADXL345_Single_Write(ADXL345_REG_INT_ENABLE,0x80);   //
   
   ADXL345_Single_Write(ADXL345_REG_OFSX,0x00);   //
   ADXL345_Single_Write(ADXL345_REG_OFSY,0x00);   //
   ADXL345_Single_Write(ADXL345_REG_OFSZ,0x00);   //
   
   return 0;
}

void ADXL345_power_down(void)
{
   ADXL345_Single_Write(ADXL345_REG_BW_RATE,0x00);   //
   ADXL345_Single_Write(ADXL345_REG_POWER_CTL,0x00);   //
   ADXL345_Single_Write(ADXL345_REG_INT_ENABLE,0x00);   // 
}

